package com.gpt.article.service.impl.taskHandle;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.LinkedBlockingQueue;

/**
 * hzb ++ 使用泛型接收任务队列
 */
@Service
public class RunDataImpl extends RunGenData {
    private static Logger logger = LoggerFactory.getLogger(XigaoThread.class);

    // url
    //未访问队列
    private volatile LinkedBlockingQueue<Object> unVisitedUrlQueue = new LinkedBlockingQueue<>();     // 待采集URL池
    private volatile Set<Object> visitedUrlSet = Collections.synchronizedSet(new HashSet<>());        // 已采集URL池

    public  void addElementToQueue( Object element) {
        unVisitedUrlQueue.add(element);
    }

    @Override
    public <T> T addTask(T gptGenTaskEntity) {
        //支持重复
//        if (!"0".equals(gptGenTaskEntity.getStatus())|| !ObjectUtils.isEmpty(gptGenTaskEntity.getTaskId()) ) {
//            logger.info(">>>>>>>>>>> 文章洗稿状态，过滤: {}", gptGenTaskEntity.getTitle());
//            return false; // check 文章状态
//        }
        if (visitedUrlSet.contains(gptGenTaskEntity)) {
            logger.info(">>>>>>>>>>> 任务已在队列中");
            return gptGenTaskEntity; // check是否洗生成过
        }
        if (unVisitedUrlQueue.contains(gptGenTaskEntity)) {
            logger.info(">>>>>>>>>>>  addTask fail, gptGenTaskEntity visited");
            return gptGenTaskEntity; // check 未记录过
        }
        unVisitedUrlQueue.add(gptGenTaskEntity);

        return (T)gptGenTaskEntity;
    }




    @Override
    public <T> T getGptTask() {
        Object gptGenTaskEntity = null;
        try {
            gptGenTaskEntity =  unVisitedUrlQueue.take();
        } catch (InterruptedException e) {
//            System.out.println("执行任务中断."+e.getMessage());
        }
        if (gptGenTaskEntity != null) {
            visitedUrlSet.add(gptGenTaskEntity);
        }
        return (T)gptGenTaskEntity;
    }

    @Override
    public int getGptNum() {
        return unVisitedUrlQueue.size();
    }
}
